package com.hougong.lineclient.transport;



import com.hougong.lineclient.Dispather;
import com.hougong.lineclient.common.GlobalCode;
import com.hougong.lineclient.common.GlobalData;
import com.hougong.lineclient.request.LoginRequest;
import com.hougong.lineclient.utils.SendUtils;
import com.hougong.lineclient.utils.SpringContextUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;


/**
 * 最终接收数据的业务Handler ，可能会有树多个判断 分支
 * 1.根据不同的业务提取命令  做判断 获取硬件信息，
 * 2.再按照协议组装不同的消息，然后传给编码器，发送二进制数据
 *
 * @author Yohann.
 */
public class AcceptHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER=LoggerFactory.getLogger(AcceptHandler.class);
    private static final String TAG="AcceptHandler";
    public static  AtomicBoolean needReConn=new AtomicBoolean(true);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof BaseFrame) {
            BaseFrame baseFrame= (BaseFrame) msg;
            Dispather dispather = (Dispather) SpringContextUtils.getBean(Dispather.class);
            dispather.handler(baseFrame,ctx.channel());
        } else {
            throw new IllegalArgumentException("msg is not instance of MessageHolder");
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info(ctx.channel().remoteAddress()+"--------连接到服务器----");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("---------与服务器断开了----------服务器："+ctx.channel().remoteAddress());
        HeartBeatTask.getInstance().cancelTask();
        ClientConfig.channel=null;
        if(needReConn.get()){
            //重新登录
            LOGGER.info("----------等待重连------");
            while (ClientConfig.channel==null){
                ClientConfig.getInstance().connectToServer();
            }
            LOGGER.info("----------重连成功------");

            if(StringUtils.isNotBlank(GlobalData.inputUserName)&&StringUtils.isNotBlank(GlobalData.inputPassword)){
                LOGGER.info("----------重新登录中...------");
                LoginRequest loginRequest=new LoginRequest();
                loginRequest.setPassword(GlobalData.inputPassword);
                loginRequest.setPasswordLen((short) GlobalData.inputPassword.getBytes().length);
                loginRequest.setUserName(GlobalData.inputUserName);
                loginRequest.setUserNameLen((short) GlobalData.inputUserName.getBytes().length);
                SendUtils.sendRequest(GlobalCode.Client_Login.getBizCode(), loginRequest);
                HeartBeatTask.getInstance().startTask();
            }else {
                needReConn.compareAndSet(true,false);
                LOGGER.info("-----长时间没有登录 断开连接！----");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }

}
